package com.adcc.test.gwtester;

import java.util.Hashtable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.wb.swt.SWTResourceManager;

import com.ibm.mq.MQC;
import com.ibm.mq.MQEnvironment;
import com.ibm.mq.MQException;
import com.ibm.mq.MQGetMessageOptions;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQPutMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;
import com.ibm.mq.MQSimpleConnectionManager;
import com.ibm.mq.constants.CMQC;

public class MainForm {

	private Shell shell;
	
	// ACTIVEMQ
	
	private Session session;
	
	private MessageConsumer consumer;
	
	private MessageProducer producer;
	
	private int txtSendNum;

	private int txtRecvNum;	
	
	private ScheduledExecutorService serviceACM;
	
	// IBMMQ
	private int txtSendNumIBM;

	private int txtRecvNumIBM;	
	
	private MQQueueManager ibmqm;
	
	private MQQueue consumerIBM;
	
	private MQGetMessageOptions consumerGmo;
	
	private MQQueue producerIBM;
	
	private MQPutMessageOptions producerGmo;
	
	private ScheduledExecutorService serviceIBM;
	
	/**
	 * Open the window.
	 */
	public void open() {
		Display display = Display.getDefault();
		createContents();
		shell.open();
		shell.layout();
		try {
			Configuration.getInstance().load();
		} catch (Exception ex) {
			Log.error("load configuration fail");
			MessageBox messageBox = new MessageBox(shell);
			messageBox.setText("提示");
			messageBox.setMessage("读取配置文件失败");
			messageBox.open();
		}
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}

	/**
	 * Create contents of the window.
	 * @wbp.parser.entryPoint
	 */
	protected void createContents() {
		shell = new Shell(SWT.DIALOG_TRIM | SWT.CLOSE | SWT.RESIZE);
		shell.setSize(1620, 650);
		shell.setText("网关测试程序");
		int x = (Display.getDefault().getBounds().width - shell.getBounds().width)/2;
		int y = (Display.getDefault().getBounds().height - shell.getBounds().height)/2;
		shell.setLocation(x, y);
		
		menu = new Menu(shell, SWT.BAR);
		shell.setMenuBar(menu);
		
		menuItemFile = new MenuItem(menu, SWT.CASCADE);
		menuItemFile.setText("文件");
		
		menuFile = new Menu(shell,SWT.DROP_DOWN);
		menuItemFile.setMenu(menuFile);
		
		menuItemExit = new MenuItem(menuFile, SWT.CASCADE);
		menuItemExit.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				menuItemExitClick(e);
			}
		});
		menuItemExit.setText("退出");
		
		// ACTIVEMQ
		grpACM = new Group(shell, SWT.NONE);
		grpACM.setText("ActiveMQ");
		grpACM.setBounds(10, 10, 790, 570);
		
		grpSend = new Group(grpACM, SWT.NONE);
		grpSend.setText("发送");
		grpSend.setBounds(251, 20, 533, 213);
		
		txtSend = new Text(grpSend, SWT.BORDER | SWT.V_SCROLL | SWT.MULTI);
		txtSend.setBounds(10, 21, 513, 182);
		
		grpConfig = new Group(grpACM, SWT.NONE);
		grpConfig.setText("配置");
		grpConfig.setBounds(10, 20, 235, 213);
		
		lblURL = new Label(grpConfig, SWT.NONE);
		lblURL.setBounds(35, 25, 28, 17);
		lblURL.setText("URL:");
		
		txtURL = new Text(grpConfig, SWT.BORDER);
		txtURL.setBounds(69, 22, 153, 23);
		txtURL.setText("tcp://192.168.247.99:61616");
		
		lblQSend = new Label(grpConfig, SWT.NONE);
		lblQSend.setBounds(12, 62, 51, 17);
		lblQSend.setText("发送队列:");
		
		txtQSend = new Text(grpConfig, SWT.BORDER);
		txtQSend.setBounds(69, 59, 153, 23);
		txtQSend.setText("QUEUE.UP");
		
		lblQRecv = new Label(grpConfig, SWT.NONE);
		lblQRecv.setBounds(12, 99, 51, 17);
		lblQRecv.setText("接收队列:");
		
		txtQRecv = new Text(grpConfig, SWT.BORDER);
		txtQRecv.setBounds(69, 96, 153, 23);
		txtQRecv.setText("QUEUE.DOWN");
		
		lblInterval = new Label(grpConfig, SWT.NONE);
		lblInterval.setBounds(12, 137, 51, 17);
		lblInterval.setText("发送间隔:");
		
		txtInterval = new Text(grpConfig, SWT.BORDER);
		txtInterval.setBounds(69, 134, 45, 23);
		txtInterval.setText("50");
		
		lblExpired = new Label(grpConfig, SWT.NONE);
		lblExpired.setBounds(120, 137, 51, 17);
		lblExpired.setText("超时时间:");
		
		txtExpired = new Text(grpConfig, SWT.BORDER);
		txtExpired.setBounds(177, 134, 45, 23);
		
		btnConnect = new Button(grpConfig, SWT.NONE);
		btnConnect.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				btnACMConnectExitClick(e);
			}
		});
		btnConnect.setBounds(26, 173, 60, 27);
		btnConnect.setText("连接");
		
		btnSend = new Button(grpConfig, SWT.NONE);
		btnSend.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				btnACMSend(e);
			}
		});
		btnSend.setBounds(92, 173, 60, 27);
		btnSend.setText("发送");
		
		btnCancel = new Button(grpConfig, SWT.NONE);
		btnCancel.setBounds(162, 173, 60, 27);
		btnCancel.setText("取消发送");
		btnCancel.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				shutdownTimerServiceACM(e);
			}
		});
		
		grpState = new Group(grpACM, SWT.NONE);
		grpState.setBounds(10, 239, 235, 313);
		
		lblState = new Label(grpState, SWT.NONE);
		lblState.setBounds(12, 26, 51, 17);
		lblState.setText("连接状态:");
		
		cmpState = new Composite(grpState, SWT.NONE);
		cmpState.setBackground(SWTResourceManager.getColor(SWT.COLOR_RED));
		cmpState.setBounds(69, 24, 153, 23);
		
		lblSendConut = new Label(grpState, SWT.NONE);
		lblSendConut.setBounds(12, 66, 51, 17);
		lblSendConut.setText("发送计数:");
		
		txtSendCount = new Text(grpState, SWT.BORDER);
		txtSendCount.setBounds(69, 62, 153, 23);
		
		lblRecvCount = new Label(grpState, SWT.NONE);
		lblRecvCount.setBounds(12, 102, 51, 17);
		lblRecvCount.setText("接收计数:");
		
		txtRecvCount = new Text(grpState, SWT.BORDER);
		txtRecvCount.setBounds(69, 98, 153, 23);
		
		clearSendCountButton = new Button(grpState, SWT.NONE);
		clearSendCountButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				clearText(e, txtSendCount);
			}
		});
		clearSendCountButton.setBounds(20, 140, 85, 27);
		clearSendCountButton.setText("清空发送计数");
		
		clearReceiveCountButton = new Button(grpState, SWT.NONE);
		clearReceiveCountButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				clearText(e, txtRecvCount);
			}
		});
		clearReceiveCountButton.setBounds(125, 140, 85, 27);
		clearReceiveCountButton.setText("清空接收计数");
		
		grpRecv = new Group(grpACM, SWT.NONE);
		grpRecv.setText("接收");
		grpRecv.setBounds(251, 239, 533, 313);
		
		txtRecv = new Text(grpRecv, SWT.BORDER | SWT.READ_ONLY | SWT.V_SCROLL | SWT.MULTI | SWT.WRAP);
		txtRecv.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		txtRecv.setBounds(10, 22, 513, 282);
		
		// IBMMQ
		grpIBM = new Group(shell, SWT.NONE);
		grpIBM.setText("IBMMQ");
		grpIBM.setBounds(810, 10, 790, 570);
		
		grpSendIBM = new Group(grpIBM, SWT.NONE);
		grpSendIBM.setText("发送");
		grpSendIBM.setBounds(251, 20, 533, 213);
		
		txtSendIBM = new Text(grpSendIBM, SWT.BORDER | SWT.V_SCROLL | SWT.MULTI);
		txtSendIBM.setBounds(10, 21, 513, 182);
		
		grpConfigIBM = new Group(grpIBM, SWT.NONE);
		grpConfigIBM.setText("配置");
		grpConfigIBM.setBounds(10, 20, 235, 354);
		
		lblHostIBM = new Label(grpConfigIBM, SWT.NONE);
		lblHostIBM.setBounds(10, 25, 40, 25);
		lblHostIBM.setText("HOST:");
		
		txtHostIBM = new Text(grpConfigIBM, SWT.BORDER);
		txtHostIBM.setText("192.168.247.97");
		txtHostIBM.setBounds(69, 22, 153, 23);
		
		lblPortIBM = new Label(grpConfigIBM, SWT.NONE);
		lblPortIBM.setBounds(10, 62, 40, 25);
		lblPortIBM.setText("PORT:");
		
		txtPortIBM = new Text(grpConfigIBM, SWT.BORDER);
		txtPortIBM.setBounds(69, 62, 153, 23);
		txtPortIBM.setText("1415");
		
		lblQMIBM = new Label(grpConfigIBM, SWT.NONE);
		lblQMIBM.setBounds(10, 99, 25, 25);
		lblQMIBM.setText("QM:");
		
		txtQMIBM = new Text(grpConfigIBM, SWT.BORDER);
		txtQMIBM.setBounds(69, 99, 153, 23);
		txtQMIBM.setText("AMQS1");
		
		lblCHIBM = new Label(grpConfigIBM, SWT.NONE);
		lblCHIBM.setBounds(10, 136, 53, 25);
		lblCHIBM.setText("CHL:");
		
		txtCHIBM = new Text(grpConfigIBM, SWT.BORDER);
		txtCHIBM.setBounds(69, 136, 153, 23);
		txtCHIBM.setText("CHL.AMQS1");
		
		lblQSendIBM = new Label(grpConfigIBM, SWT.NONE);
		lblQSendIBM.setBounds(10, 173, 51, 17);
		lblQSendIBM.setText("发送队列:");
		
		txtQSendIBM = new Text(grpConfigIBM, SWT.BORDER);
		txtQSendIBM.setBounds(69, 173, 153, 23);
		txtQSendIBM.setText("AMQS1.DOWN");
		
		lblQRecvIBM = new Label(grpConfigIBM, SWT.NONE);
		lblQRecvIBM.setBounds(10, 210, 51, 17);
		lblQRecvIBM.setText("接收队列:");
		
		txtQRecvIBM = new Text(grpConfigIBM, SWT.BORDER);
		txtQRecvIBM.setBounds(69, 210, 153, 23);
		txtQRecvIBM.setText("AMQS1.UP");
		
		lblIntervalIBM = new Label(grpConfigIBM, SWT.NONE);
		lblIntervalIBM.setBounds(12, 247, 51, 17);
		lblIntervalIBM.setText("发送间隔:");
		
		txtIntervalIBM = new Text(grpConfigIBM, SWT.BORDER);
		txtIntervalIBM.setBounds(69, 247, 45, 23);
		txtIntervalIBM.setText("50");
		
		lblExpiredIBM = new Label(grpConfigIBM, SWT.NONE);
		lblExpiredIBM.setBounds(120, 247, 51, 17);
		lblExpiredIBM.setText("超时时间:");
		
		txtExpiredIBM = new Text(grpConfigIBM, SWT.BORDER);
		txtExpiredIBM.setBounds(177, 247, 45, 23);
		txtExpiredIBM.setText("360000");
		
		btnConnectIBM = new Button(grpConfigIBM, SWT.NONE);
		btnConnectIBM.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				btnIBMConnectExitClick(e);
			}
		});
		btnConnectIBM.setBounds(26, 285, 60, 27);
		btnConnectIBM.setText("连接");
		
		btnSendIBM = new Button(grpConfigIBM, SWT.NONE);
		btnSendIBM.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				btnIBMSend(e);
			}
		});
		btnSendIBM.setBounds(92, 285, 60, 27);
		btnSendIBM.setText("发送");
		btnSendIBM.setEnabled(false);
		
		btnCancelIBM = new Button(grpConfigIBM, SWT.NONE);
		btnCancelIBM.setBounds(162, 285, 60, 27);
		btnCancelIBM.setText("取消发送");
		btnCancelIBM.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				shutdownTimerServiceIBM(e);
			}
		});
		btnCancelIBM.setEnabled(false);
		
		btnDisconnectIBM = new Button(grpConfigIBM, SWT.NONE);
		btnDisconnectIBM.setBounds(26, 317, 60, 27);
		btnDisconnectIBM.setText("断开");
		btnDisconnectIBM.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				btnIBMDisconnect(e);
			}
		});
		btnDisconnectIBM.setEnabled(false);
		
		grpStateIBM = new Group(grpIBM, SWT.NONE);
		grpStateIBM.setBounds(10, 380, 235, 170);
		
		lblStateIBM = new Label(grpStateIBM, SWT.NONE);
		lblStateIBM.setBounds(12, 26, 51, 17);
		lblStateIBM.setText("连接状态:");
		
		cmpStateIBM = new Composite(grpStateIBM, SWT.NONE);
		cmpStateIBM.setBackground(SWTResourceManager.getColor(SWT.COLOR_RED));
		cmpStateIBM.setBounds(69, 24, 153, 23);
		
		lblSendConutIBM = new Label(grpStateIBM, SWT.NONE);
		lblSendConutIBM.setBounds(12, 66, 51, 17);
		lblSendConutIBM.setText("发送计数:");
		
		txtSendCountIBM = new Text(grpStateIBM, SWT.BORDER);
		txtSendCountIBM.setBounds(69, 62, 153, 23);
		
		lblRecvCountIBM = new Label(grpStateIBM, SWT.NONE);
		lblRecvCountIBM.setBounds(12, 102, 51, 17);
		lblRecvCountIBM.setText("接收计数:");
		
		txtRecvCountIBM = new Text(grpStateIBM, SWT.BORDER);
		txtRecvCountIBM.setBounds(69, 98, 153, 23);
		
		clearSendCountButtonIBM = new Button(grpStateIBM, SWT.NONE);
		clearSendCountButtonIBM.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				clearText(e, txtSendCountIBM);
			}
		});
		clearSendCountButtonIBM.setBounds(20, 140, 85, 27);
		clearSendCountButtonIBM.setText("清空发送计数");
		
		clearReceiveCountButtonIBM = new Button(grpStateIBM, SWT.NONE);
		clearReceiveCountButtonIBM.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				clearText(e, txtRecvCountIBM);
			}
		});
		clearReceiveCountButtonIBM.setBounds(125, 140, 85, 27);
		clearReceiveCountButtonIBM.setText("清空接收计数");
		
		grpRecvIBM = new Group(grpIBM, SWT.NONE);
		grpRecvIBM.setText("接收");
		grpRecvIBM.setBounds(251, 239, 533, 313);
		
		txtRecvIBM = new Text(grpRecvIBM, SWT.BORDER | SWT.READ_ONLY | SWT.V_SCROLL | SWT.MULTI | SWT.WRAP);
		txtRecvIBM.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		txtRecvIBM.setBounds(10, 22, 513, 282);
	}
	
	private void clearText(SelectionEvent e, Text text) {
		try {
			text.setText("");
		} catch (Exception ex) {
			Log.error("clearText() " + text + " error:", ex);
		}
	}
	
	private void btnACMConnectExitClick(SelectionEvent e){
		try{
			String strURL = txtURL.getText().trim();
			String strUsername = Configuration.getInstance().getUsername();
			String strPassword = Configuration.getInstance().getPassword();
			if (session == null) {
				ActiveMQConnectionFactory amcf = new ActiveMQConnectionFactory(strUsername,strPassword, strURL);
				//构造从工厂得到连接对象
				Connection connection = amcf.createConnection();
				//启动
				connection.start();
				//获取操作连接
				session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
				if (session != null) {
					cmpState.setBackground(SWTResourceManager.getColor(SWT.COLOR_GREEN));
					btnConnect.setEnabled(false);
				}
			}
            //获取队列
			if (consumer == null) {
				Destination recvQueue = session.createQueue(txtQRecv.getText().trim());
				consumer = session.createConsumer(recvQueue);
			}
            
            new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						while (true) {
			                final TextMessage message =(TextMessage) consumer.receive();
			                if (null != message) {
			                    Display.getDefault().syncExec(new Runnable() {
			                        public void run() {
			                        	try {
											txtRecv.append("\n\r" + message.getText());
											txtRecvCount.setText(String.valueOf(++txtRecvNum));
										} catch (JMSException e) {
											e.printStackTrace();
										} 
			                        }
			                    }); 
			                } else {
			                    break;
			                }
			            }
					} catch (Exception e) {
						Log.error("receive message error: " + e.getMessage());
					}
				}
			}).start();
		}catch(Exception ex){
			Log.error("btnConnectExitClick() error",ex);
			cmpState.setBackground(SWTResourceManager.getColor(SWT.COLOR_RED));
			btnConnect.setEnabled(true);
		}
	}
	
	private void btnACMSend(SelectionEvent e) {
		try {
			if (session == null )
				return;
			
			if (producer == null) {
				Destination sendQueue = session.createQueue(txtQSend.getText().trim());
				producer = session.createProducer(sendQueue);
			}
			
			final String msg = txtSend.getText();
			
			Runnable runnable = new Runnable() {	
				@Override
				public void run() {
					try {
						if (msg != null && !msg.isEmpty()) {
							TextMessage outMessage = session.createTextMessage();
							outMessage.setText(msg);
							producer.send(outMessage);
							
							Display.getDefault().syncExec(new Runnable() {
			                    public void run() {
			                    	txtSendCount.setText(String.valueOf(++txtSendNum));
			                    }
			                }); 
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			};
			
			serviceACM = Executors  
	                .newSingleThreadScheduledExecutor();  
			serviceACM.scheduleAtFixedRate(runnable, 0, Integer.parseInt(txtInterval.getText().trim()), TimeUnit.MILLISECONDS);
		} catch (Exception ex) {
			Log.error("btnSend error: " + ex);
		}
	}
	
	private void shutdownTimerServiceACM(SelectionEvent e) {
		try {
			if (serviceACM != null) {
				serviceACM.shutdown();
			}
		} catch (Exception ex) {
			Log.error("shutdownTimerService error: " + ex);
		}
	}
	
	private void btnIBMConnectExitClick(SelectionEvent e) {
		try {
			// 设置连接管理器
			MQSimpleConnectionManager simpleConnectionManager = new MQSimpleConnectionManager();
			simpleConnectionManager.setActive(Configuration.getInstance().getActiveModeACM());
			simpleConnectionManager.setTimeout(Long.valueOf(txtExpiredIBM.getText().trim()));
	        MQEnvironment.setDefaultConnectionManager(simpleConnectionManager);
	        // 每次连接重新重新初始化管理器
        	Hashtable<Object,Object> properties = new Hashtable<Object,Object>();
        	String strQM = txtQMIBM.getText().trim();
        	properties.put(MQC.HOST_NAME_PROPERTY,txtHostIBM.getText().trim());
        	properties.put(MQC.PORT_PROPERTY, Integer.valueOf(txtPortIBM.getText().trim()));
        	properties.put(MQC.CHANNEL_PROPERTY,txtCHIBM.getText().trim());
        	ibmqm = new MQQueueManager(strQM,properties,simpleConnectionManager);
            // 每次连接重新初始化接收队列
        	int consumerIntOptions = CMQC.MQOO_INPUT_AS_Q_DEF | CMQC.MQOO_INQUIRE |CMQC.MQOO_FAIL_IF_QUIESCING;
        	consumerIBM = ibmqm.accessQueue(txtQRecvIBM.getText().trim(), consumerIntOptions);
            consumerGmo = new MQGetMessageOptions();
            consumerGmo.options = CMQC.MQGMO_NO_WAIT | CMQC.MQGMO_CONVERT | CMQC.MQGMO_FAIL_IF_QUIESCING;
            // 每次连接重新初始化发送队列
            int producerIntOptions = CMQC.MQOO_OUTPUT | CMQC.MQOO_INQUIRE | CMQC.MQOO_FAIL_IF_QUIESCING;
			producerIBM = ibmqm.accessQueue(txtQSendIBM.getText().trim(), producerIntOptions);
			producerGmo = new MQPutMessageOptions();
			producerGmo.options = CMQC.MQPMO_FAIL_IF_QUIESCING;
			
			// 改变界面显示
            if (ibmqm.isConnected()) {
            	cmpStateIBM.setBackground(SWTResourceManager.getColor(SWT.COLOR_GREEN));
				btnConnectIBM.setEnabled(false);
				btnSendIBM.setEnabled(true);
				btnCancelIBM.setEnabled(false);
				btnDisconnectIBM.setEnabled(true);
            }
			
            // 定义接收报文的任务
            Runnable runnbale = new Runnable() {
            	@Override
                public void run() {
            		
    				while(true) {
						try {
							if (ibmqm == null || !ibmqm.isConnected()) {
								break;
							}
							
							if (consumerIBM.getCurrentDepth() <= 0 || !consumerIBM.isOpen()) {
    							continue;
    						}
    						
    						MQMessage message = new MQMessage();
    						message.characterSet = 1208;
    						consumerIBM.get(message, consumerGmo);
    		                int msgLength = message.getTotalMessageLength();
    		                if (msgLength > 0) {
    		                	byte[] data = new byte[msgLength];
    			                message.readFully(data, 0, data.length);
    			                final String strMsg = new String(data, 0, data.length);
    			                
    			                Display.getDefault().syncExec(new Runnable() {
    		                        public void run() {
    									txtRecvIBM.append("\n\r" + strMsg);
    									txtRecvCountIBM.setText(String.valueOf(++txtRecvNumIBM));
    		                        }
    		                    }); 
    		                } else {
    		                    break;
    		                }
    					} catch (Exception ex) {
    						if (ex instanceof MQException) {
    							MQException e = (MQException) ex;
    							int reason = e.reasonCode;
        						if (reason == 2033) {
        							Log.error("no message"); 
        						}
    						} else {
    							Log.error("IBM send runnable error", ex);
    						}
    	    			}
					}
	    		}
	    	};
	    	// 执行收报任务
	    	Thread t = new Thread(runnbale);
	    	t.setDaemon(true);
	    	t.start();
	    	
		} catch(Exception ex) {
			Log.error("btnIBMConnectExitClick() error",ex);
			cmpStateIBM.setBackground(SWTResourceManager.getColor(SWT.COLOR_RED));
			btnConnectIBM.setEnabled(true);
			btnSendIBM.setEnabled(false);
			btnCancelIBM.setEnabled(false);
			btnDisconnectIBM.setEnabled(false);
		}
	}

	private void btnIBMSend(SelectionEvent e) {
		try {
			if(ibmqm == null || !ibmqm.isConnected()) {
				return;
			}
            
            btnSendIBM.setEnabled(false);
            btnCancelIBM.setEnabled(true);
            
            // 定义发送任务
            final String msg = txtSendIBM.getText();
            Runnable runnable = new Runnable() {	
				@Override
				public void run() {
					try {
						if (msg != null && !msg.isEmpty()) {
							//Log.info(Thread.currentThread() + " " + msg);
							MQMessage mqm = new MQMessage();
			                mqm.characterSet = 1208;
			                mqm.write(msg.getBytes(),0,msg.length());
			                producerIBM.put(mqm, producerGmo);
							
							Display.getDefault().syncExec(new Runnable() {
			                    public void run() {
			                    	txtSendCountIBM.setText(String.valueOf(++txtSendNumIBM));
			                    }
			                }); 
						}
					} catch (Exception e) {
						Log.error("send message failed!", e);
					}
				}
			};
			// 定时执行发报任务
			serviceIBM = Executors.newSingleThreadScheduledExecutor();
			serviceIBM.scheduleAtFixedRate(runnable, 0, Integer.parseInt(txtIntervalIBM.getText().trim()), TimeUnit.MILLISECONDS);  
		} catch (Exception ex) {
			Log.error("btnIBMSend error()", ex);
		}
	}
	
	private void shutdownTimerServiceIBM(SelectionEvent e) {
		try {
			if (serviceIBM != null) {
				serviceIBM.shutdown();
			}
			
			btnSendIBM.setEnabled(true);
			btnCancelIBM.setEnabled(false);
			Log.info("shutdownTimerServiceIBM success");
		} catch (Exception ex) {
			Log.error("shutdownTimerServiceIBM error()", ex);
		}
	}
	
	private void btnIBMDisconnect(SelectionEvent e) {
		try {
			// 取消发送
			shutdownTimerServiceIBM(e);
			// 断开连接
			if (ibmqm != null) {
				ibmqm.disconnect();
				ibmqm.close();
			}
			// 初始化界面显示
        	cmpStateIBM.setBackground(SWTResourceManager.getColor(SWT.COLOR_RED));
			btnConnectIBM.setEnabled(true);
			btnSendIBM.setEnabled(false);
			btnCancelIBM.setEnabled(false);
			btnDisconnectIBM.setEnabled(false);
			
			Log.info("btnIBMDisconnect success");
		} catch (Exception ex) {
			Log.error("btnIBMDisconnect() error", ex);
		}
	}
	
	private void menuItemExitClick(SelectionEvent e) {
		try{
			Display.getDefault().close();
		}catch(Exception ex){
			Log.error("menuItemExitClick() error", ex);
		}
	}
	
	private Menu menu;
	private Menu menuFile;
	private MenuItem menuItemFile;
	private MenuItem menuItemExit;
	
	private Group grpACM;
	private Group grpConfig;
	private Label lblURL;
	private Text txtURL;
	private Label lblQSend;
	private Text txtQSend;
	private Label lblQRecv;
	private Text txtQRecv;
	private Label lblInterval;
	private Text txtInterval;
	private Label lblExpired;
	private Text txtExpired;
	private Button btnConnect;
	private Button btnSend;
	private Button btnCancel;
	private Group grpState;
	private Label lblState;
	private Composite cmpState;
	private Label lblSendConut;
	private Label lblRecvCount;
	private Text txtSendCount;
	private Text txtRecvCount;
	private Group grpSend;
	private Text txtSend;
	private Group grpRecv;
	private Text txtRecv;
	private Button clearReceiveCountButton;
	private Button clearSendCountButton;
	
	private Group grpIBM;
	private Group grpConfigIBM;
	private Label lblHostIBM;
	private Text txtHostIBM;
	private Label lblPortIBM;
	private Text txtPortIBM;
	private Label lblQMIBM;
	private Text txtQMIBM;
	private Label lblCHIBM;
	private Text txtCHIBM;
	private Label lblQSendIBM;
	private Text txtQSendIBM;
	private Label lblQRecvIBM;
	private Text txtQRecvIBM;
	private Label lblIntervalIBM;
	private Text txtIntervalIBM;
	private Label lblExpiredIBM;
	private Text txtExpiredIBM;
	private Button btnConnectIBM;
	private Button btnSendIBM;
	private Button btnCancelIBM;
	private Button btnDisconnectIBM;
	private Group grpStateIBM;
	private Label lblStateIBM;
	private Composite cmpStateIBM;
	private Label lblSendConutIBM;
	private Label lblRecvCountIBM;
	private Text txtSendCountIBM;
	private Text txtRecvCountIBM;
	private Group grpSendIBM;
	private Text txtSendIBM;
	private Group grpRecvIBM;
	private Text txtRecvIBM;
	private Button clearReceiveCountButtonIBM;
	private Button clearSendCountButtonIBM;
}
